//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.mongodb3;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.bytecode.MethodInfo;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * 简书  javaagent
 *
 *
 */
public class MobsAgentClassTransfer implements ClassFileTransformer {
    private static final String classPath = "com.mongodb3.service.HelloServiceImpl";

    private static final String replace = classPath.replaceAll("\\.", "/");

    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if (className.equals(replace)) {
            try {
                ClassPool cPool = new ClassPool();
                cPool.appendSystemPath();
                CtClass declaring = cPool.get(classPath);
                CtMethod saySomething = declaring.getDeclaredMethod("saySomething");
                saySomething.setName("saySomething$OldMethod");
                CtMethod newMethod = CtNewMethod.copy(saySomething, "saySomething", declaring, null);
                newMethod.setName("saySomething");
                newMethod.setBody("{" +
                        "       com.mongodb3.MobsAgentClassTransfer.proxyMethod($$); \n" +
                        "      return  saySomething$OldMethod($$);" +
                        "}"
                );
                //获取方法信息
                MethodInfo methodInfo = saySomething.getMethodInfo();
//                newMethod.getMethodInfo().addAttribute();
                declaring.addMethod(newMethod);
                return declaring.toBytecode();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return classfileBuffer;
    }

    public static void proxyMethod(String hello) {
        System.out.println("ClassFileTransformerImp.proxyMethod , i'm called.");
    }
}
